const app = getApp();
const util = require('../../utils/util.js');
const config = require('../../utils/config.js');
const auth = require('../../utils/auth.js');
Page({
  data: {
    account: '',
    password: '',
    disabled: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  onLoad:function(){
    this.isLogin();
  },
  onShow:function(){
    auth.authsetting();
  },

  isLogin:function(){
    let _this = this;
    util.showBusy('用户匹配中...');
    _this.getCode().then(res => {
     return res.code;
    }).catch(res=>{
      console.error('wxloginErro')
    }).then(res=>{
      let code = res;
      util.request()({
        url: config.config.service.loginUrl + '/miniProgram-getOpenId',
        data: {
          code: encodeURI(code),
        },
      }).then(res => {
        if (res.data.err_no == -1) throw new Error(res.data.msg);
        console.info('openid', res.data.openid)
        app.globalData.openId = res.data.openid;
        return res.data.openid;
      }).catch(res => {
        util.showModel('', res.message);
      }).then(res=>{
        let openid = res;
        util.request()({
          url: config.config.service.loginUrl + '/miniProgram-checkDBOpenId',
          data: {
            openid: encodeURI(openid),
          },
        }).then(res=>{
          wx.hideToast();
          _this.setData({ disabled:false})
          if (res.data.err_no == -1) throw new Error(res.data.msg);
          let accountDB = res.data.account;
          if (!accountDB){
            throw new Error("没获取到白名单用户信息.");
          }
          app.globalData.account = accountDB;
          wx.setStorageSync("ACCOUNT", accountDB);
          wx.navigateTo({
            url: '../index/index',
          })
        }).catch(res=>{
          console.info('checkDBOpenId', res.message)
        })
      })
    })
  },

  login: function (userInfo) {
    let _this = this;
    if (_this.data.account.length == 0 || _this.data.password.length == 0) {
      util.showModel('', '账号.密码不能为空.');
    }else{
      util.showBusy('登录中...');
      if (!app.globalData.openId){
        util.showModal('获取OpenId失败无法登陆','联系管理员解决此问题')
        return;
      }
      util.request()({
        url: config.config.service.loginUrl + '/miniProgram-mplogin',
        data: {
          openid: encodeURI(app.globalData.openId),
          account: encodeURI(_this.data.account),
          password: encodeURI(_this.data.password),
        },
      }).then(res=>{
        wx.hideToast();
        if (res.data.err_no == -1) throw new Error(res.data.msg);
        wx.setStorageSync("ACCOUNT", res.data.account);
        app.globalData.account = res.data.account;
        console.log('loginAccount', res.data.account);
        wx.navigateTo({
          url: '../index/index',
        })
      }).catch(res=>{
        util.showModel('', res.message);
      })
    }
  },
 
  // 获取code
  getCode: function () {
    return util.MyPromise(wx.login)()
  },
  
  openSetting:function(){
    return util.MyPromise(wx.openSetting)();
  },

  getUserInfo:function(){
    return util.MyPromise(wx.getUserInfo)();
  },

  // 获取用户信息
  onGotUserInfo: function (e) {
    let _this = this;
    console.log(e)
    console.log(e.detail.errMsg)
    if (e.detail.errMsg == 'getUserInfo:ok'){
      _this.login(e.userInfo);
    }else{
      console.log('不允许获取用户信息')
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
        success: function (res) {
          if (res.confirm) {
            _this.openSetting().then(res=>{
              return res.authSetting["scope.userInfo"];
            }).catch(res=>{
              console.error('用户授权失败.');
            }).then(res =>{
              if (res) {//如果用户重新同意了授权登录
                _this.getUserInfo().then(res => {
                  app.globalData.userInfo = res.userInfo ? res.userInfo : null;
                  console.info('userInfo',res.userInfo);
                })
              }
            })

          }
        }
      })
      
    }
  },
  // 获取输入账号
  accountInput: function (e) {
    this.setData({
      account: e.detail.value
    })
  },

  // 获取输入密码
  passwordInput: function (e) {
    this.setData({
      password: e.detail.value
    })
  },
})
